document.addEventListener('DOMContentLoaded', function() {
    const videoPlayer = document.getElementById('videoPlayer');
    const videoUrl = document.getElementById('videoUrl');
    const playButton = document.getElementById('playButton');
    const formatSelector = document.getElementById('formatSelector');
    const playPauseBtn = document.getElementById('playPauseBtn');
    const muteBtn = document.getElementById('muteBtn');
    const volumeSlider = document.getElementById('volumeSlider');
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    const progressBar = document.getElementById('progressBar');
    const progressFill = document.getElementById('progressFill');
    const currentTime = document.getElementById('currentTime');
    const duration = document.getElementById('duration');
    const speedSelector = document.getElementById('speedSelector');
    const localFileBtn = document.getElementById('localFileBtn');
    const fileInput = document.getElementById('fileInput');
    const fileName = document.getElementById('fileName');
    let hls = null;

    // 存储当前视频URL
    let currentVideoUrl = '';

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }

    function initializePlayer(url, isLocalFile = false) {
        if (hls) {
            hls.destroy();
        }

        currentVideoUrl = url;
        const format = formatSelector.value;
        
        if (format === 'm3u8' && !isLocalFile) {
            if (Hls.isSupported()) {
                hls = new Hls();
                hls.loadSource(url);
                hls.attachMedia(videoPlayer);
                hls.on(Hls.Events.MANIFEST_PARSED, function() {
                    videoPlayer.play();
                    updatePlayPauseButton();
                });
            } else if (videoPlayer.canPlayType('application/vnd.apple.mpegurl')) {
                videoPlayer.src = url;
                videoPlayer.addEventListener('loadedmetadata', function() {
                    videoPlayer.play();
                    updatePlayPauseButton();
                });
            } else {
                alert('您的浏览器不支持 HLS 格式视频播放');
            }
        } else {
            videoPlayer.src = url;
            videoPlayer.play();
            updatePlayPauseButton();
        }

        // 保存播放信息到storage
        chrome.storage.local.set({
            lastVideo: {
                url: url,
                format: format,
                isLocal: isLocalFile,
                currentTime: 0
            }
        });
    }

    function updatePlayPauseButton() {
        const icon = playPauseBtn.querySelector('i');
        if (videoPlayer.paused) {
            icon.className = 'fas fa-play';
        } else {
            icon.className = 'fas fa-pause';
        }
    }

    function updateMuteButton() {
        const icon = muteBtn.querySelector('i');
        if (videoPlayer.muted) {
            icon.className = 'fas fa-volume-mute';
        } else {
            if (videoPlayer.volume > 0.5) {
                icon.className = 'fas fa-volume-up';
            } else if (videoPlayer.volume > 0) {
                icon.className = 'fas fa-volume-down';
            } else {
                icon.className = 'fas fa-volume-off';
            }
        }
    }

    // 本地文件处理
    localFileBtn.addEventListener('click', function() {
        fileInput.click();
    });

    fileInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            fileName.textContent = file.name;
            const url = URL.createObjectURL(file);
            // 根据文件扩展名自动选择格式
            const ext = file.name.split('.').pop().toLowerCase();
            if (ext === 'm3u8') {
                formatSelector.value = 'm3u8';
            } else {
                formatSelector.value = 'mp4';
            }
            initializePlayer(url, true);
        }
    });

    playButton.addEventListener('click', function() {
        const url = videoUrl.value.trim();
        if (!url) {
            alert('请输入视频 URL');
            return;
        }
        initializePlayer(url);
    });

    formatSelector.addEventListener('change', function() {
        const url = videoUrl.value.trim();
        if (url) {
            initializePlayer(url);
        }
    });

    playPauseBtn.addEventListener('click', function() {
        if (videoPlayer.paused) {
            videoPlayer.play();
        } else {
            videoPlayer.pause();
        }
        updatePlayPauseButton();
    });

    muteBtn.addEventListener('click', function() {
        videoPlayer.muted = !videoPlayer.muted;
        if (!videoPlayer.muted) {
            videoPlayer.volume = volumeSlider.value / 100;
        }
        updateMuteButton();
    });

    volumeSlider.addEventListener('input', function() {
        videoPlayer.volume = this.value / 100;
        videoPlayer.muted = false;
        updateMuteButton();
    });

    fullscreenBtn.addEventListener('click', function() {
        // 创建新标签页播放视频
        if (currentVideoUrl) {
            // 保存当前播放时间
            const currentTime = videoPlayer.currentTime;
            const format = formatSelector.value;
            
            // 创建新的标签页
            chrome.tabs.create({
                url: 'player.html'
            }, function(tab) {
                // 等待新标签页加载完成后发送视频信息
                chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
                    if (tabId === tab.id && info.status === 'complete') {
                        chrome.tabs.onUpdated.removeListener(listener);
                        chrome.tabs.sendMessage(tab.id, {
                            type: 'PLAY_VIDEO',
                            url: currentVideoUrl,
                            format: format,
                            currentTime: currentTime
                        });
                    }
                });
            });
        }
    });

    progressBar.addEventListener('click', function(e) {
        const rect = this.getBoundingClientRect();
        const pos = (e.clientX - rect.left) / rect.width;
        videoPlayer.currentTime = pos * videoPlayer.duration;
    });

    speedSelector.addEventListener('change', function() {
        videoPlayer.playbackRate = parseFloat(this.value);
    });

    videoPlayer.addEventListener('timeupdate', function() {
        const pos = (videoPlayer.currentTime / videoPlayer.duration) * 100;
        progressFill.style.width = `${pos}%`;
        currentTime.textContent = formatTime(videoPlayer.currentTime);
        
        // 保存当前播放时间
        if (currentVideoUrl) {
            chrome.storage.local.set({
                lastVideo: {
                    url: currentVideoUrl,
                    format: formatSelector.value,
                    currentTime: videoPlayer.currentTime
                }
            });
        }
    });

    videoPlayer.addEventListener('loadedmetadata', function() {
        duration.textContent = formatTime(videoPlayer.duration);
    });

    videoPlayer.addEventListener('play', updatePlayPauseButton);
    videoPlayer.addEventListener('pause', updatePlayPauseButton);
    videoPlayer.addEventListener('volumechange', updateMuteButton);

    // 恢复上次播放的视频
    chrome.storage.local.get('lastVideo', function(data) {
        if (data.lastVideo && data.lastVideo.url) {
            videoUrl.value = data.lastVideo.url;
            formatSelector.value = data.lastVideo.format;
            initializePlayer(data.lastVideo.url);
            videoPlayer.currentTime = data.lastVideo.currentTime;
        }
    });
}); 